﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.BasicData.Employees;
using mozhi.smarterp.BasicData.Employees.Repositories;
using mozhi.smarterp.BasicData.EntityFrameworkCore;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace mozhi.smarterp.BasicData.Repositories
{
    public class EmployeeRepository : EfCoreRepository<BasicDataDbContext, Employee, Guid>, IEmployeeRepository
    {
        public EmployeeRepository(IDbContextProvider<BasicDataDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<int> GetCountAsync(string code, Guid? excludeId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            int count = await dbContext.Set<Employee>().AsNoTracking()
                .WhereIf(!code.IsNullOrEmpty(), x => x.Code == code)
                .WhereIf(excludeId.HasValue, x => x.Id != excludeId)
                .CountAsync(cancellationToken);

            return count;
        }

        public async Task<List<Employee>> GetPagedListAsync(string keyword, bool? activated, Guid? departmentId, int skipCount, int maxResultCount, string sorting, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            var employees = await dbContext.Set<Employee>().AsNoTracking()
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(departmentId.HasValue, x => x.DepartmentId != null && x.DepartmentId != departmentId)
                .WhereIf(activated.HasValue, x => x.Activated == activated)
                .OrderByIf<Employee, IQueryable<Employee>>(!sorting.IsNullOrWhiteSpace(), sorting)
                .PageBy(skipCount, maxResultCount).ToListAsync(GetCancellationToken(cancellationToken));

            return employees;
        }

        public async Task<int> GetCountAsync(string keyword, bool? activated, Guid? departmentId, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync();

            int count = await dbContext.Set<Employee>().AsNoTracking()
                .WhereIf(!keyword.IsNullOrEmpty(), x => x.Code.Contains(keyword) || x.Name.Contains(keyword))
                .WhereIf(departmentId.HasValue, x => x.DepartmentId != null && x.DepartmentId != departmentId)
                .WhereIf(activated.HasValue, x => x.Activated == activated)
                .CountAsync(cancellationToken);

            return count;
        }
    }
}
